//
//  TYCEmoticonInputView.swift
//  TheEmoticon
//
//  Created by tangyunchuan on 2018/8/9.
//  Copyright © 2018年 tangyunchuan. All rights reserved.
//

import UIKit

/// 可重用的标识符
private let cellId = "cellId"

/// 表情输入视图
class TYCEmoticonInputView: UIView {

    @IBOutlet weak var collectionView: UICollectionView!
    // 分页控件
    @IBOutlet weak var pageContrl: UIPageControl!
    // 底部工具栏
    @IBOutlet weak var toolBar: TYCEmoticonToolBar!
    //选中表情回调闭包属性
    private var selectedEmoticonCallBack: ((_ emticon: TYCEmoticon?) -> ())?
    
    /// 加载并且返回输入视图
    class func inputView(selectedEmoticon: @escaping (_ emticon: TYCEmoticon?) -> ()) -> TYCEmoticonInputView {
        
        let nib = UINib(nibName: "TYCEmoticonInputView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! TYCEmoticonInputView
        //记录闭包
        v.selectedEmoticonCallBack = selectedEmoticon
        return v
    }
    
    override func awakeFromNib() {
        //注册可重用cell
        collectionView.register(TYCEmticonCell.self, forCellWithReuseIdentifier: cellId)
        //设置工具栏代理
        toolBar.delegate = self
        //设置分页控件的图片
        let bundle = TYCEmoticonManager.share.bundle
        guard let normalImage = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil),
            let selectedImage = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else {
                return
        }
        //使用填充色图片设置颜色
//        pageContrl.pageIndicatorTintColor = UIColor(patternImage: normalImage)
//        pageContrl.currentPageIndicatorTintColor = UIColor(patternImage: selectedImage)
        //使用KVC 设置私有成员属性
        pageContrl.setValue(normalImage, forKey: "_pageImage")
        pageContrl.setValue(selectedImage, forKey: "_currentPageImage")
    }
}

extension TYCEmoticonInputView: TYCEmoticonToolBarDelegate {
    func emoticonToolBarDidSelectedItemIndex(toolBar: TYCEmoticonToolBar, index: Int) {
        /// 让 collectionView 发生滚动 -> 没一个分组的第0页
        let indexPath = IndexPath(item: 0, section: index)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        //设置分组按钮的选中状态
        toolBar.selectedIndex = index
    }
}

extension TYCEmoticonInputView: UICollectionViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //1. 获取中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        //2. 获取当前显示的 cell 的 indexPath
        let paths = collectionView.indexPathsForVisibleItems
        //3. 判断中心点在哪一个 indexPath上，在哪一个页面上
        var  targetIndexPath: IndexPath?
        
        for indexPath in paths {
            //1> 根据 indexPath 获取 cell
            let cell = collectionView.cellForItem(at: indexPath)
            //2> 判断中心点位置
            if cell?.frame.contains(center) == true {
                targetIndexPath = indexPath
                break
            }
        }
        guard let target = targetIndexPath else {
            return
        }
        //4. 判断是否找到目标的 indexPath
        //indexPath.section => 对应的就是分组
        toolBar.selectedIndex = target.section
        //5. 设置分页控件
        //1> 总页数， 不同的分组，页数不一样
        pageContrl.numberOfPages = collectionView.numberOfSections
        pageContrl.currentPage = target.item
    }
}

extension TYCEmoticonInputView: UICollectionViewDataSource {
    //分组数据 - 返回表情包的数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }
    //返回每个分组中的表情‘页’的数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 8
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //取 cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TYCEmticonCell
        //设置 cell ,传递对应页面的表情数组
        cell.emoticons = TYCEmoticonManager.share.packages[indexPath.section].emoticon(page: indexPath.item)
        //设置代理
        cell.delegate = self;
        //返回 cell
        return cell
    }
}

// MARK: - TYCEmticonCellDelegate
extension TYCEmoticonInputView: TYCEmticonCellDelegate {
    /// 选中的表情包回调
    ///
    /// - Parameters:
    ///   - cell: 分页cell
    ///   - em: 选中的表情，删除键为nil
    func emticonCellDidSelectedEmoticon(cell: TYCEmticonCell, em: TYCEmoticon?) {
//        print(em)
        /// 执行闭包，回调选中的表情
        selectedEmoticonCallBack?(em)
        /// 添加最近使用的表情
        guard let em = em else {
            return
        }
        //如果当前的collectionView就是最近的分组，不添加最近使用表情
        let indexPath = collectionView.indexPathsForVisibleItems[0]
        if indexPath.section == 0 {
            return
        }
        //添加最近使用的表情
        TYCEmoticonManager.share.recentEmoticon(em: em)
        
        //刷新数据 -- 第零组
        var indexSet = IndexSet()
        indexSet.insert(0)
        
        collectionView.reloadSections(indexSet)
    }
}
